import 'package:nfc_sbk/nfc_sbk.dart';
import '../utils/helpers.dart';
import "dart:typed_data";
import 'dart:convert';
class NfcReader{
  static NfcReader _nfcReader;
  NfcReader._internal();
  NfcReader get instance=>_nfcReader;
  factory NfcReader() {
    if (_nfcReader==null) {
      _nfcReader=NfcReader._internal();
    }
    return _nfcReader;
  }

  bool isStopRead;

  Future<String> readSbk() async{
    isStopRead=false;
    String result;
    while (!isStopRead) {
      //延迟0.5s
      await Future.delayed(Duration(milliseconds: 500));
      //A 读卡信息
      result = await NfcSbk.writeIsoDep([
        'A',
        '00A404000F7378312E73682EC9E7BBE1B1A3D5CF',
        '00A4000002EF05',
        '00B207040B'
      ]);
     if(result!=null) return result;
    }
    return null;
  }
  //私钥签名
  //priKey 相关文件hash后的签名
  Future<String> signSbk(String priKey) async{
    isStopRead=false;
    String result;
    while (!isStopRead) {
      //延迟0.5s
      await Future.delayed(Duration(milliseconds: 500));
      //B 私钥签名
      result = await NfcSbk.writeIsoDep([
        'B',
      '00A404000C504B492EC9E7BBE1B1A3D5CF',//指令
      '00A4000002DF01',//指令
      '0084000010',//指令
      '3DE741F445DD357BEA4E6C3FE6437036',//加密密钥
       priKey
      ]);
     if(result!=null) return result;
    }
    return null;
  }
  Future<String> writeIsoDep(List<String> args) async{
    isStopRead=false;
    String result;
    while (!isStopRead) {
      //延迟0.5s
      await Future.delayed(Duration(milliseconds: 500));

      result = await NfcSbk.writeIsoDep(args);
     if(result!=null) return result;
    }
    return null;
  }
  Future<String> encryptData_ECB(List<String> args) async{
   return await NfcSbk.encryptData_ECB(args);
  }
  Future<void> stopReadSbk() async{
    isStopRead=true;
    await NfcSbk.stopNFC();
  }
  Future<String> checkNFC() async{
    String status=await NfcSbk.checkNFC();
    return status;
  }

  String resolving(String str){
    if(str.startsWith("0709")){
      str=str.substring(4);
      str=str.replaceFirst('9000', '',15);
    }else{
      return str;
    }
    Uint8List uint8list=createUint8ListFromHexString(str);
    return (utf8.decode(uint8list));
  }
}